<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div>
    <div style="margin-bottom: 5px; text-align: center;">
      <el-input 
        placeholder="请输入资讯标题" 
        :prefix-icon="Search" 
        v-model="name"
        style="width: 200px; margin-left: 5px" 
        @keyup.enter="loadPost()"
      />
      
      <el-button 
        type="success" 
        :icon="Search" 
        circle 
        style="margin-left: 5px;" 
        @click="loadPost()"
        v-if="hasAuth('system:article-search')"
      />
      
      <el-button 
        type="primary" 
        :icon="Refresh" 
        circle 
        style="margin-left: 5px;"
        @click="resetParam()"
      />

      <el-button 
        type="primary" 
        :icon="Plus" 
        circle 
        style="margin-left: 5px;" 
        @click="add()"
        v-if="hasAuth('system:article-save')"
      />
      
      <el-button 
        type="danger" 
        :icon="Delete" 
        circle 
        style="margin-left: 5px;" 
        @click="delHandle(null)"
        v-if="hasAuth('system:article-delete')" 
        :disabled="delBtnStatus"
      />
    </div>
    
    <el-table 
      ref="multipleTableRef" 
      :data="tableData" 
      tooltip-effect="dark" 
      border 
      style="width: 100%" 
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column prop="name" label="资讯名称" />
      
      <el-table-column prop="cover" label="资讯展示" width="150">
        <template #default="scope">
          <img :src="scope.row.cover" min-width="70" height="70" />
        </template>
      </el-table-column>
      
      <el-table-column prop="content" label="资讯内容" width="700px">
        <template #default="scope">
          <div v-html="scope.row.content"></div>
        </template>
      </el-table-column>
      
      <el-table-column 
        prop="createTime" 
        label="创建时间" 
        width="200" 
        :formatter="formatDate"
      />
      
      <el-table-column fixed="right" label="操作" width="150px" prop="operate">
        <template #default="scope">
          <el-button 
            type="primary" 
            :icon="Edit" 
            circle 
            @click="mod(scope.row)"
            style="margin-left: 5px;" 
            v-if="hasAuth('system:article-update')"
          />
          
          <el-button 
            type="danger" 
            :icon="Delete" 
            circle 
            style="margin-left: 5px;"
            @click="delHandle(scope.row.id)" 
            v-if="hasAuth('system:article-delete')"
          />
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="pageNum"
      :page-size="pageSize" 
      :page-sizes="[5, 10, 50, 100]" 
      background
      layout="total,sizes,prev, pager, next,jumper" 
      :total="total"
    />
    
    <el-dialog 
      v-model="centerDialogVisible" 
      title="资讯增改表单" 
      width="80%" 
      center
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px" 
        style="width: 1200px; margin: 10px auto"
        enctype="multipart/form-data"
      >
        <el-form-item label="资讯名称" prop="name">
          <el-input v-model="form.name" style="width:1000px;" />
        </el-form-item>
        
        <el-form-item label="资讯封面" prop="cover">
          <el-upload 
            action="#" 
            list-type="picture-card" 
            :auto-upload="false"
            :on-exceed="handleExceed" 
            accept="image/*" 
            :on-change="submitUpload"
            :file-list="fileList" 
            :limit="1"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="资讯内容" prop="content">
          <WangEditor 
            v-model="form.content" 
            :content="form.content" 
            style="width: 1000px;" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// eslint-disable-next-line vue/multi-word-component-names
import { ref, reactive, onMounted, computed } from 'vue'
import { 
  Search, 
  Refresh, 
  Plus, 
  Delete, 
  Edit 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Store } from '@/store/index'
import api from '@/axios/index'
// 假设 WangEditor 已经正确导入和注册为全局组件

// 获取 store 实例
const store = Store()

// refs
const multipleTableRef = ref()
const formRef = ref()

// 数据响应式
const pageSize = ref(5)
const pageNum = ref(1)
const total = ref(0)
const tableData = ref([])
const centerDialogVisible = ref(false)
const delBtnStatus = ref(true)
const multipleSelection = ref([])
const fileList = ref([])
const name = ref("")

const form = reactive({
  id: "",
  name: "",
  cover: null,
  content: ""
})

const rules = {
  name: [
    { required: true, message: '资讯名称不能为空', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入资讯内容', trigger: 'blur' }
  ],
  cover: [
    { required: true, message: '请上传资讯展示图片', trigger: 'change' }
  ]
}

// 计算属性
const hasAuth = computed(() => {
  return function (perm) {
    return store.permList.includes(perm)
  }
})

// 方法
const resetParam = () => {
  name.value = ""
}

const formatDate = (row, column) => {
  let data = row[column.property]
  if (data == null) {
    return null
  }
  let dt = new Date(data)
  return (
    dt.getFullYear() +
    "-" +
    (dt.getMonth() + 1) +
    "-" +
    dt.getDate() +
    " " +
    dt.getHours() +
    ":" +
    dt.getMinutes() +
    ":" +
    dt.getSeconds()
  )
}

const add = () => {
  centerDialogVisible.value = true
  resetForm()
}

const mod = (row) => {
  // 赋值到表单
  api.get("/article/info/" + row.id).then((res) => {
    Object.assign(form, res.data)

    if (form.cover != "") {
      fileList.value = []
      fileList.value.push({
        url: form.cover,
      })
    }

    centerDialogVisible.value = true
  })
}

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.id) {
        doMod()
      } else {
        doSave()
      }
    } else {
      ElMessage({
        message: "请填写正确数据",
        type: "error",
      })
      return false
    }
  })
}

const doSave = () => {
  api.post("/article/save", form)
    
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        })
        centerDialogVisible.value = false
        loadPost()
        resetForm()
      } else {
        ElMessage({
          message: res.msg,
          type: "error",
        })
      }
    })
}

const doMod = () => {
  api.post("/article/update", form)
    
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        })
        centerDialogVisible.value = false
        loadPost()
        resetForm()
      } else {
        ElMessage({
          message: res.msg,
          type: "error",
        })
      }
    })
}

const handleExceed = (files) => {
  console.log(files)
  ElMessage.error("只能上传一张图片")
}

const submitUpload = (file) => {
  const config = {
    headers: {}
  }
  let fd = new FormData()
  fd.append("file", file.raw)
  fd.append("name", file.name)

  api.post("/file/upload", fd, config).then((res) => {
    console.log(res)
    if (res.code == 200) {
      form.cover = res.data.url
      // 存储返回的数据
      ElMessage({
        message: "上传成功！",
        type: "success"
      })
    } else {
      ElMessage({
        message: "上传失败",
        type: "error"
      })
    }
  })
}

const resetForm = () => {
  Object.assign(form, {
    id: "",
    name: "",
    cover: null,
    content: ""
  })

  fileList.value = []
}

const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`)
  pageNum.value = 1
  pageSize.value = val
  loadPost()
}

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`)
  pageNum.value = val
  loadPost()
}

const loadPost = () => {
  api.post("/article/listPage", {
    pageSize: pageSize.value,
    pageNum: pageNum.value,
    param: {
      name: name.value,
    },
  })
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        tableData.value = res.data
        if (res.length == 0 && pageNum.value != 1) {
          pageNum.value = 1
          loadPost()
        }
        total.value = res.total
      } else {
        ElMessage({
          message: "数据查询失败",
          type: "warning",
        })
      }
    })
}

const delHandle = (id) => {
  console.log(id)
  var ids = []
  if (id) {
    ids.push(id)
  } else {
    multipleSelection.value.forEach((row) => {
      ids.push(row.id)
    })
  }
  
  ElMessageBox.confirm("将删除资讯一切有关数据， 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    api.post("/article/deleteBatch", ids, {
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
      },
    }).then((res) => {
      console.log(res)
      ElMessage({
        showClose: true,
        message: "恭喜你，操作成功",
        type: "success",
      })
      loadPost()
    }).catch((err) => {
      console.error(err)
      ElMessage({
        showClose: true,
        message: "操作失败，请重试",
        type: "error",
      })
    })
  }).catch(() => {
    ElMessage({
      showClose: true,
      message: "已取消操作",
      type: "info",
    })
  })
}


const handleSelectionChange = (val) => {
  multipleSelection.value = val
  delBtnStatus.value = val.length == 0
}

// 生命周期
onMounted(() => {
  loadPost()
})
</script>
<style scoped>
.el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>